package com.dongdongshop.mq;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.pojo.pay.TbPayLog;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.service.PayLogService;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RocketMQMessageListener(topic = "orderStatus",consumerGroup = "orderStatus-consumer")//配置消费者信息
public class MQconsumer implements RocketMQListener<String>,RocketMQPushConsumerLifecycleListener{

    @Reference
    private PayLogService payLogService;

    @Reference
    private OrderService orderService;

    @Override
    public void onMessage(String s) {
        System.out.println("消息消费成功"+s);
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer consumer) {
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                MessageExt message = list.get(0);//消息在list中
                try {
                    //获取主题
                    String messageBody = new String(message.getBody(), "utf-8");
                    //根据母订单id(消息内容）查询paylog中有没有已支付数据。
                    // 如果没有，则根据所有orderid(消息内容)更新order表数据为失效商品
                    //System.out.println("payOrder"+messageBody);
                    TbPayLog payLog = payLogService.selectByOutTradeNo(messageBody);
                    if(payLog != null){
                        String orderList = payLog.getOrderList();
                        String order = orderList.substring(0,orderList.length()-1);
                        String[] split = order.split(",");
                        for (int i = 0; i < split.length; i++) {
                            orderService.updateStatusById(Long.parseLong(split[i]));
                        }
                    }
                    System.out.println("ACK消息消费成功"+messageBody);
                } catch (Exception e) {
                    // e.printStackTrace();
                    //报错处理(记录日志，错误信息)
                    System.out.println("消息消费失败，稍后再试");
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
    }
}
